package cn.edu.hunau.dao.impl;


import cn.edu.hunau.dao.OrderDao;
import cn.edu.hunau.exception.DaoException;
import cn.edu.hunau.pojo.Address;
import cn.edu.hunau.pojo.Order;
import cn.edu.hunau.pojo.User;
import cn.edu.hunau.utils.DBUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author 苏佳
 * @Date 2022 11 13 21 31
 **/
public class OrderDaoImpl implements OrderDao {
    @Override
    public void insert(Order order) throws DaoException {
        String sql="insert into t_order (id,account,uid) values(?,?,?)";
        DBUtils.updateTransaction(sql,order.getId(),order.getAccount(),order.getUser().getId());
    }

    @Override
    public void updateAid(String oid, int aid) throws DaoException {
        String sql="update t_order SET aid=? WHERE id=?";
        DBUtils.updateTransaction(sql,aid,oid);
    }

    @Override
    public void updateOstate(String oid) throws DaoException {
        System.out.println(oid);
        //FIX:
        String sql="update t_order SET ostate='2' WHERE id=?";
        DBUtils.updateTransaction(sql,oid);
    }

    @Override
    public List<Order> queryByUid(int uid) throws DaoException {
        String sql="select id,account,ostate,aid,uid,dotime from t_order where uid=?";
        return DBUtils.query(sql,rs -> {
            ArrayList<Order> datas = new ArrayList<>();
            Order o=null;
            User u=null;
            Address a=null;
            while (rs.next()){
                o=new Order();
                u=new User();
                a=new Address();
                o.setId(rs.getString("id"));
                o.setAccount(rs.getDouble("account"));
                o.setOstate(rs.getString("ostate"));
                a.setId(rs.getInt("aid"));
                o.setAddress(a);
                u.setId(rs.getInt("uid"));
                o.setUser(u);

                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                o.setDotime(LocalDateTime.parse(rs.getString("dotime"),df));
                datas.add(o);
            }
            return datas;
        },uid);
    }

    @Override
    public void deleteOrderByOid(String oid) throws DaoException {
        String sql="delete from t_order where id=?";
        DBUtils.updateTransaction(sql,oid);
    }

    @Override
    public int countByOstate(int uid,String ostate) throws DaoException {
        String sql="select count(id) from t_order where uid=? and ostate=?";
        return DBUtils.query(sql,rs -> {
            int count=-1;
            while(rs.next()){
                count = rs.getInt(1);
            }
            return count;
        },uid,ostate);
    }
}
